package com.example.ceshi.ui.home;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.ceshi.Bean.BrandDetail;
import com.example.ceshi.Bean.DataDetail;
import com.example.ceshi.Bean.DetailBean;
import com.example.ceshi.Bean.Details;
import com.example.ceshi.Bean.NowUserData;
import com.example.ceshi.BrandActivity;
import com.example.ceshi.DetailActivity;
import com.example.ceshi.EditTextSearch;
import com.example.ceshi.R;
import com.example.ceshi.SQLite.MySQLiteOpenHelper;
import com.example.ceshi.adapter.DetailAdapter2;
import com.example.ceshi.databinding.FragmentHomeBinding;
import com.example.ceshi.utils.DestroyActivityUtil;
import com.example.ceshi.utils.NetUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


//主页
public class HomeFragment extends Fragment implements View.OnClickListener {
    //    假数据 正是情况通过数据库查询
    private String[] kuaidiNo;
    private MySQLiteOpenHelper mySQLiteOpenHelper;

    private FragmentHomeBinding binding;
    private String s = "";
    private String TAG = "ning";
    private String TAG2 = "ming";
    private BrandDetail brandDetail;
    private String strData = "";
    private DetailBean detailBean;
    private Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                strData = (String) msg.obj;
                imageView = dialog.findViewById(R.id.brandImg);
                text_name = dialog.findViewById(R.id.brandname);
                text_number = dialog.findViewById(R.id.number);
//                    Log.d(TAG2,"得到的数据:"+strData);
                parseJsonData(strData);
                if (Objects.equals(brandDetail.getCode(), "200")) {
                    Details details = brandDetail.getData().getDetails().get(0);
                    Log.d(TAG2, details.toString());

                    text_name.setText(details.getExpressName());
                    text_number.setText("单号：" + s);
                    switch (details.getExpressCode()) {
                        case "SF":
                            imageView.setImageResource(R.drawable.sf);
                            break;
                        case "YTO":
                            imageView.setImageResource(R.drawable.yuantong);
                            break;
                        case "ZTO":
                            imageView.setImageResource(R.drawable.zhongtong);
                            break;
                        case "YUNDA":
                            imageView.setImageResource(R.drawable.yunda);
                            break;
                        case "STO":
                            imageView.setImageResource(R.drawable.shentong);
                            break;
                        case "TTKDEX":
                            imageView.setImageResource(R.drawable.tiantian);
                            break;
                        case "JD":
                            imageView.setImageResource(R.drawable.jingdong);
                            break;
                        case "EMS":
                            imageView.setImageResource(R.drawable.youzheng);
                            break;
                        case "DBKD":
                            imageView.setImageResource(R.drawable.debang);
                            break;
                        case "DBL":
                            imageView.setImageResource(R.drawable.debang);
                            break;
                        case "DBKY":
                            imageView.setImageResource(R.drawable.debang);
                            break;
                    }
                    Toast.makeText(getContext(), "成功查询到信息", Toast.LENGTH_LONG).show();
                } else {
                    text_name.setText("未查询到数据");
                    text_number.setText("未查询到数据");
                    //未查到详细信息
                    Toast.makeText(getContext(), "未查询到信息", Toast.LENGTH_LONG).show();
                }
                Log.d(TAG2, "封装的brandbean:" + brandDetail.toString());

            }
        }
    };

    //初始化用户所有包裹数据
    private Handler mHandler2 = new Handler(Looper.myLooper()) {
        //        父线程接受信息
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                strData = (String) msg.obj;

                parseJsonData2(strData);
                if (detailBean!=null&&Objects.equals(detailBean.getCode(), "200")) {
                    NowUserData.dataDetailList.add(detailBean.getData());

                }
            }
        }
    };
    private ImageView imageView;
    private TextView text_name;
    private TextView text_number;
    private Dialog dialog;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

//        final TextView textView = binding.textHome;
//        homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        mySQLiteOpenHelper=new MySQLiteOpenHelper(getContext());
        List<String> results =mySQLiteOpenHelper.selectExpressNoByUsername(NowUserData.id.toString());
        kuaidiNo=results.toArray(new String[results.size()]);
//        Log.d(TAG2,results.toString());
//        view.findViewById(R.id.btn_home).setOnClickListener(this);
        view.findViewById(R.id.btn_detail).setOnClickListener(this);
        view.findViewById(R.id.btn_brand).setOnClickListener(this);

        if (NowUserData.dataDetailList == null) {
            NowUserData.dataDetailList = new ArrayList<>();
            for (int i = 0; i < kuaidiNo.length; i++) {
//                NetUtil.getDetails(kuaidiNo[i]);
                getDetail(kuaidiNo[i]);
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    public void parseJsonData(String jsonStr) {

        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
//            DataDetail dataDetail =(DataDetail)jsonObject.getJSONObject("data");
            Gson gson = new Gson();
//            封装成的Bean对象 里面放的是物流的详细信息
            brandDetail = gson.fromJson(jsonStr, BrandDetail.class);
//            Log.d(TAG2,"开始执行了");
            Log.d(TAG2, brandDetail.toString());

//            jsonObject.get
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void parseJsonData2(String jsonStr) {

        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
//            DataDetail dataDetail =(DataDetail)jsonObject.getJSONObject("data");
            Gson gson = new Gson();
//            封装成的Bean对象 里面放的是物流的详细信息
            detailBean = gson.fromJson(jsonStr, DetailBean.class);
//            Log.d(TAG2,"开始执行了");
            Log.d(TAG2, detailBean.toString());

//            jsonObject.get
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        String regex = "[a-zA-Z]*\\d+";
        EditTextSearch editTextSearch = getView().findViewById(R.id.search_text);
        s = editTextSearch.getText().toString();
        if (s == null || s == "") {
            Toast.makeText(getContext(), "请输入内容", Toast.LENGTH_SHORT).show();
        } else if (!s.matches(regex)) {
            Toast.makeText(getContext(), "请输入规范内容", Toast.LENGTH_SHORT).show();
        } else {

            if (view.getId() == R.id.btn_detail) {
//            去物流详细页面
                Bundle bundle = new Bundle();
                bundle.putString("number", s);
                intent.putExtras(bundle);

                intent.setClass(getActivity(), DetailActivity.class);

                startActivity(intent);
            } else if (view.getId() == R.id.btn_brand) {
//            去物流品牌页面
                dialog = new Dialog(getContext());
                View inflate = getLayoutInflater().inflate(R.layout.activity_brand, null);

                Button btn = inflate.findViewById(R.id.btn_back);

                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });

                getBrand(s);

                dialog.setContentView(inflate);
                dialog.show();
            }


        }


    }


    public void getBrand(String number) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String stringFromNet = NetUtil.getBrand(number);

                Message message = new Message();
                message.what = 0;
                message.obj = stringFromNet;

                mHandler.sendMessage(message);
            }
        }).start();
//        Toast.makeText(this, "任务完成", Toast.LENGTH_LONG).show();
    }

    public void getDetail(String number) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                String stringFromNet = NetUtil.getDetails(number);


                Message message = new Message();
                message.what = 0;
                message.obj = stringFromNet;

                mHandler2.sendMessage(message);
            }
        }).start();
    }

    private long exitTime=0;


}

